package leetcode;

import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 描述:146. LRU 缓存
 *
 * @author Madison You
 * @created 1:05
 */
public class Mid_146_LRUCache {

    public static void main(String[] args) {
        LRULinkedHashMap lRUCache = new LRULinkedHashMap(4);
        lRUCache.put(9,3);
        lRUCache.put(7,4);
        lRUCache.put(9,4);
        lRUCache.put(5,9);
        lRUCache.put(3,4);
        lRUCache.put(6,6);
    }

    LinkedList<Integer> queue = null;

    Map<Integer, Integer> map = new HashMap<>();

    private int capacity;

    private int size = 0;

    public Mid_146_LRUCache(int capacity) {
        this.queue = new LinkedList<>();
        this.capacity = capacity;
    }

    public int get(int key) {
        Integer integer = map.get(key);
        if (integer == null) {
            return -1;
        } else {
            queue.remove((Object) key);
            queue.offer(key);
            return integer;
        }
    }

    public void put(int key, int value) {
        Integer integer = map.get(key);
        if (integer == null) {
            if (size >= capacity) {
                Integer poll = queue.poll();
                map.remove(poll);
                size--;
            }
        } else {
            queue.remove((Object) key);
            size--;
        }
        map.put(key, value);
        queue.offer(key);
        size++;
    }

    static class LRULinkedHashMap<K,V> extends LinkedHashMap<K,V> {
        //定义缓存的容量
        private int capacity;
        private static final long serialVersionUID = 1L;
        //带参数的构造器
        LRULinkedHashMap(int capacity){
            //调用LinkedHashMap的构造器，传入以下参数
            super(16,0.75f,true);
            //传入指定的缓存最大容量
            this.capacity=capacity;
        }
        //实现LRU的关键方法，如果map里面的元素个数大于了缓存最大容量，则删除链表的顶端元素
        @Override
        public boolean removeEldestEntry(Map.Entry<K, V> eldest){
            System.out.println(eldest.getKey() + "=" + eldest.getValue());
            return size()>capacity;
        }
    }

}
